/**
 * 
 */
package org.javarosa.cdctz.util;

import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;

import org.javarosa.core.Context;
import org.javarosa.core.JavaRosaServiceProvider;
import org.javarosa.core.api.Constants;
import org.javarosa.core.api.IActivity;
import org.javarosa.core.api.ICommand;
import org.javarosa.core.api.IShell;
import org.javarosa.core.services.storage.utilities.IRecordStoreEnumeration;
import org.javarosa.core.services.storage.utilities.RecordStorageException;
import org.javarosa.core.util.Map;
import org.javarosa.formmanager.view.Commands;
import org.javarosa.patient.storage.PatientMetaDataObject;
import org.javarosa.patient.storage.PatientRMSUtility;

/**
 * @author Brian DeRenzi
 *
 */
public class TempPatientSelectActivity implements IActivity {
	public static final int VIEW_TYPE_PATIENT_SELECT = 66;
	
	public static final String COMMAND_KEY = "command";
	public static final String PATIENT_ID_KEY = "patient_id";
	
	private TempPatientList patientList = null;
	private Map listOfPatients = null;
	private Vector patientIDs = null;
	private IShell parent = null;
	private Vector positionToId = null;
	
	Context context;
	
	public TempPatientSelectActivity(IShell p, String title) {
		this.parent = p;
		this.patientList = new TempPatientList(this,title);
	}
	
	public void start(Context context) {
		this.listOfPatients = new Map();
		this.patientIDs = new Vector();
		getPatients();
		this.positionToId = this.patientList.loadView(listOfPatients);
		parent.setDisplay(this, this.patientList);
		
		this.context = context;
	}
	
	
	public void viewCompleted(Hashtable returnvals, int view_ID) {
		// Determine which view just completed and act accordingly
		switch(view_ID) {
		case VIEW_TYPE_PATIENT_SELECT:
			processPatientList(returnvals);
			break;
		}
	}
	
	private void processPatientList(Hashtable returnvals) {
		Enumeration en = returnvals.keys();
		while(en.hasMoreElements()) {
			String cmd = (String)en.nextElement();

			if( cmd == TempPatientList.SELECT_PATIENT){
				int selectedPatient = ((Integer)returnvals.get(TempPatientList.SELECT_PATIENT)).intValue();
				int patientId = ((Integer)positionToId.elementAt(selectedPatient)).intValue();
				//#if debug.output==verbose
				System.out.println("Selected form: " + patientIDs.elementAt(patientId));
				//#endif
				PatientMetaDataObject meta = (PatientMetaDataObject)patientIDs.elementAt(patientId);

				Hashtable returnArgs = new Hashtable();
				returnArgs.put(PATIENT_ID_KEY, new Integer(meta.getRecordId()));
				returnArgs.put(COMMAND_KEY, TempPatientList.SELECT_PATIENT);
				parent.returnFromActivity(this, Constants.ACTIVITY_COMPLETE, returnArgs );

				break;

			} else if (cmd == Commands.CMD_EXIT) {
				Hashtable returnArgs = new Hashtable();
				returnArgs.put(COMMAND_KEY, Commands.CMD_EXIT);
				parent.returnFromActivity(this, Constants.ACTIVITY_COMPLETE, returnArgs );
			} else if (cmd == Commands.CMD_SETTINGS) {
				Hashtable returnArgs = new Hashtable();
				returnArgs.put(COMMAND_KEY, Commands.CMD_SETTINGS);
				parent.returnFromActivity(this, Constants.ACTIVITY_SUSPEND, returnArgs );
			} else if (cmd == TempPatientList.CMD_NEW_STRING) {
				Hashtable returnArgs = new Hashtable();
				returnArgs.put(COMMAND_KEY, TempPatientList.CMD_NEW_STRING);
				parent.returnFromActivity(this, Constants.ACTIVITY_NEEDS_RESOLUTION, returnArgs );
			} else if (cmd == TempPatientList.CMD_UPDATE_STRING) {
				int selectedPatient = ((Integer)returnvals.get(TempPatientList.CMD_UPDATE_STRING)).intValue();
				int patientId = ((Integer)positionToId.elementAt(selectedPatient)).intValue();
				
				PatientMetaDataObject meta = (PatientMetaDataObject)patientIDs.elementAt(patientId);

				Hashtable returnArgs = new Hashtable();
				returnArgs.put(COMMAND_KEY, TempPatientList.CMD_UPDATE_STRING);
				returnArgs.put(PATIENT_ID_KEY, new Integer(meta.getRecordId()));
				parent.returnFromActivity(this, Constants.ACTIVITY_NEEDS_RESOLUTION, returnArgs );
			}
		}
	}
	
	private void getPatients() {
		PatientRMSUtility patUtility = (PatientRMSUtility) JavaRosaServiceProvider
				.instance().getStorageManager().getRMSStorageProvider()
				.getUtility(PatientRMSUtility.getUtilityName());
		patUtility.open();
    	IRecordStoreEnumeration recordEnum = patUtility.enumerateMetaData();
    	int pos =0;
    	while(recordEnum.hasNextElement())
    	{
    		int i;
			try {
				i = recordEnum.nextRecordId();
				PatientMetaDataObject mdata = new PatientMetaDataObject();
				patUtility.retrieveMetaDataFromRMS(i,mdata);
				// TODO fix it so that record id is part of the metadata serialization
				
				listOfPatients.put(new Integer(pos), mdata.getRecordId()+" - "+mdata.getName());
				patientIDs.insertElementAt(mdata, pos);
				pos++;
			} catch (RecordStorageException e) {
				// TODO Auto-generated catch block
				//#if debug.output==verbose || debug.output==exception
				e.printStackTrace();
				//#endif
			}
		}
    }
	
	public void contextChanged(Context context) {
		Vector contextChanges = this.context.mergeInContext(context);
		
		Enumeration en = contextChanges.elements();
		while(en.hasMoreElements()) {
			String changedValue = (String)en.nextElement();
			if(changedValue == Constants.USER_KEY) {
				//update username somewhere
			}
		}
	}
	
	public void halt() {
		
	}
	public void resume(Context context) {
		this.contextChanged(context);
		getPatients();
		this.positionToId = this.patientList.loadView(listOfPatients);
		//Possibly want to check for new/updated forms
		JavaRosaServiceProvider.instance().showView(this.patientList);
	}
	public void destroy() {
		
	}
	public Context getActivityContext() {
		return context;
	}
	/*
	 * (non-Javadoc)
	 * @see org.javarosa.core.api.IActivity#setShell(org.javarosa.core.api.IShell)
	 */
	public void setShell(IShell shell) {
		this.parent = shell;
	}
	/* (non-Javadoc)
	 * @see org.javarosa.core.api.IActivity#annotateCommand(org.javarosa.core.api.ICommand)
	 */
	public void annotateCommand(ICommand command) {
		throw new RuntimeException("The Activity Class " + this.getClass().getName() + " Does Not Yet Implement the annotateCommand Interface Method. Please Implement It.");
	}
}
